<?php

namespace app\api\job;

use think\Hook;
use think\queue\Job;
use app\common\model\app\Intel;
use app\common\model\app\IntelAttachment;
use app\common\model\app\Topic;

class IntelVerify {

    /**
     * @param Job $job 任务对象
     * @param $data 数据
     * 消息队列将自动调用该方法
     */
    public function fire(Job $job, $data) {
        //从data中拿数据
        $intelJob = $this->verify($data);
        if ($intelJob !== false) {
            //任务执行完成，记得删除任务
            echo "审核任务完成(".date('Y-m-d H:i:s', time()).")：{$data['id']}\n";
            $job->delete();
        } else {
            //attempts() 可以获取当前任务已经尝试执行几次
            if ($job->attempts() > 0) {
                //假设同一个任务尝试执行了多次都失败，那么我们可能需要打印日志，甚至通知开发者人工介入
                echo "审核任务失败(".date('Y-m-d H:i:s', time()).")：{$data['id']}\n";
                $job->delete();
            }
        }
    }

    public function verify($data) {
        $id         = $data['id'];
        $user_id    = $data['user_id'];
        $images     = $data['images'];
        $content    = $data['content'];
        $vlog       = $data['vlog'];
        $result     = true;
        // $topicIds   = $data['topicArr'];

        $row = Intel::get($id);
        if ($row !== false) {
            echo "审核任务开始(".date('Y-m-d H:i:s', time()).")：{$id}\n";
            if ($row['verify'] == '1') {
                echo "已经审核，跳出队列：{$id}\n";
                return true;
            }
            //审核逻辑1:内容监测
            if ($content) {
                echo "审核内容：{$content}\n";
                $msg = '{"Content":"'.base64_encode($content).'"}';
                $res = Hook::listen('text_moderation', $msg);
                if ($res[0]['Data']['EvilFlag'] > 0 || $res[0]['Data']['EvilType'] > 100) {
                    $result = false;
                    $detailResult = $res[0]['Data']['DetailResult'];
                    $save['verifynote'] = '';
                    foreach ($detailResult as $k => $v) {
                        // $preposition . $typeText . '；' . '标签：' . $label . '；' . '分值：' . $score;
                        switch ($v['EvilType'])
                        {
                            case "20001":
                                $evilType = '政治';
                            break;
                            case "20002":
                                $evilType = '色情';
                            break;
                            case "20006":
                                $evilType = '涉毒违法';
                            break;
                            case "20007":
                                $evilType = '谩骂';
                            break;
                            case "20105":
                                $evilType = '广告引流';
                            break;
                            case "24001":
                                $evilType = '暴恐';
                            break;
                            default:
                                $evilType = '其他';
                        }
                        if( isset($v['Keywords']) ) {
                            $keywords = $v['Keywords'];
                            $keywordsCount = count($keywords);
                            $keyword = '';
                            for ($i=0; $i <= ($keywordsCount-1); $i++) {
                                if($keywordsCount > 1){
                                    if( ($keywordsCount-1) == $i){
                                        $keyword .= $keywords[$i];
                                    }else{
                                        $keyword .= $keywords[$i] . '、';
                                    }
                                }else{
                                    $keyword .= $keywords[$i];
                                }
                            }
                        }else{
                            $keyword = '';
                        }

                        $save['verifynote'] .= '文本审核不通过，恶意类型：' . $evilType . '，关键字：' . $keyword . '，分值：' . $v['Score'] . '；';
                    }
                }
            }

            //审核逻辑2:视频监测
//            if ($vlog && $result) {
//
//            }

            //审核逻辑3:图片监测
            if ($images && $result) {
                $_tmp = explode(',', $images);
                if ($_tmp) {
                    foreach ($_tmp as $item) {
                        $preg = "/^http(s)?:\\/\\/.+/";
                        if (preg_match($preg, $item)) {
                            echo "审核图片：".$item."\n";
                            $pic = '{"FileUrl":"'.$item.'"}';
                        } else {
                            echo "审核图片：https://www.0759yc.com".$item."\n";
                            $pic = '{"FileUrl":"https://www.0759yc.com'.$item.'"}';
                        }
                        $res = Hook::listen('image_moderation', $pic);
                        echo "EvilFlag：{$res[0]['Data']['EvilFlag']}\n";
                        echo "EvilType：{$res[0]['Data']['EvilType']}\n";
                        if ($res[0]['Data']['EvilFlag'] > 0 || $res[0]['Data']['EvilType'] > 100) {
                            $result = false;
                            function checkResult($labels,$score,$typeText){
                                $preposition = '图片审核不通过，恶意类型：';
                                if( $labels !== '' ){
                                    $labelsCount = count($labels);
                                    $label = '';
                                    for ($i=0; $i <= ($labelsCount-1); $i++) {
                                        if($labelsCount > 1){
                                            if( ($labelsCount-1) == $i){
                                                $label .= $labels[$i];
                                            }else{
                                                $label .= $labels[$i] . '、';
                                            }
                                        }else{
                                            $label .= $labels[$i];
                                        }
                                    }
                                }else{
                                    $labels = '';
                                }
                                return $preposition . $typeText . '；' . '标签：' . $label . '；' . '分值：' . $score;
                            }
                            switch ($res[0]['Data']['EvilType'])
                            {
                                case "20001":
                                    $faceNames = $res[0]['Data']['PolityDetect']['FaceNames'];
                                    $score = $res[0]['Data']['PolityDetect']['Score'];
                                    $save['verifynote'] = checkResult($faceNames,$score,'政治');
                                    break;
                                case "20002":
                                    $labels = $res[0]['Data']['PornDetect']['Labels'];
                                    $score = $res[0]['Data']['PornDetect']['Score'];
                                    $save['verifynote'] = checkResult($labels,$score,'色情');
                                    break;
                                case "20006":
                                    $labels = $res[0]['Data']['IllegalDetect']['Labels'];
                                    $score = $res[0]['Data']['IllegalDetect']['Score'];
                                    $save['verifynote'] = checkResult($labels,$score,'涉毒违法');
                                    break;
                                case "20007":
                                    $save['verifynote'] = '图片审核不通过,恶意类型：谩骂';
                                    break;
                                case "20103":
                                    $labels = $res[0]['Data']['HotDetect']['Labels'];
                                    $score = $res[0]['Data']['HotDetect']['Score'];
                                    $save['verifynote'] = checkResult($labels,$score,'性感');
                                    break;
                                case "24001":
                                    $labels = $res[0]['Data']['TerrorDetect']['Labels'];
                                    $score = $res[0]['Data']['TerrorDetect']['Score'];
                                    $save['verifynote'] = checkResult($labels,$score,'暴恐');
                                    break;
                                default:
                                    $save['verifynote'] = '图片审核不通过';
                            }
                        }
                        // 绑定图片到情报id
                        $_P['intel_id'] = $id;
                        IntelAttachment::where('url', $item)->where('user_id', $user_id)->update($_P);
                    }
                }
            }

            if ($result) {
                $save['verify'] = '1';
                $save['verifynote'] = '内容全部正常';
                if( $data['topicArr'] != '' ) {
                    foreach ($data['topicArr'] as $k => $v) {
                        // 发布 - 审核（1，2）- 存在
                        $topic = Topic::get($v);
                        Topic::topicRedisInc($topic->name);
                    }
                }
            } else {
                $save['verify'] = '2';
            }
            $save['verifytime'] = time();

            $res = $row->allowField(true)->save($save);
            if ($res !== false) {
                return true;
            }
        }

        return false;
    }

}
